import React, { Component } from 'react'
import styles from './index.module.scss'
import { SearchBar } from 'antd-mobile'
import { getCurrentCity } from '../../../utils/city'
import { getCommunityList } from '../../../api/rent'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { setCommunity } from '../../../store/actionCreator'
// import * as actionCreators from '../../../store/actionCreator'

class RentSearch extends Component {
  state = {
    communityList: null
  }

  debounce = (fun, delay) => {
    return function (args) {
      //获取函数的作用域和变量
      let that = this
      let _args = args
      //每次事件被触发，都会清除当前的timeer，然后重写设置超时调用
      clearTimeout(fun.id)
      fun.id = setTimeout(function () {
        fun.call(that, _args)
      }, delay)
    }
  }

  componentDidMount () {
    this.debounceSearch = this.debounce(this.search, 500)
  }

  onChange = async val => {
    this.debounceSearch(val)
  }

  search = async name => {
    const { value: id } = await getCurrentCity()

    const res = await getCommunityList(id, name)

    this.setState({
      communityList: res.data.body
    })
  }

  toggleSelect = ({ community, communityName }) => {
    // this.props.setCommunityData({ community, communityName })
    this.props.setCommunity({ community, communityName })
    this.props.history.goBack()
  }

  render () {
    const { communityList } = this.state
    return (
      <div className={styles.root}>
        <SearchBar
          placeholder='请输入小区或地址'
          onCancel={() => this.props.history.goBack()}
          onChange={this.onChange}
        />
        {communityList && (
          <ul className={styles.tips}>
            {communityList.map(item => {
              return (
                <li
                  key={item.community}
                  onClick={() => this.toggleSelect(item)}
                  className={styles.tip}
                >
                  {item.communityName}
                </li>
              )
            })}
          </ul>
        )}
      </div>
    )
  }
}

// const mapDispatchToProps = dispatch => {
//   return bindActionCreators(actionCreators, dispatch)
//   // return {
//   //   setCommunityData: function (obj) {
//   //     // 触发设置小区对象的action
//   //     dispatch(setCommunity(obj))
//   //   }
//   // }
// }

export default connect(null, { setCommunity })(RentSearch)
